package com.irdstudio.efp.esb.api.rest.yed.loanManage;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.ESBException;
import com.irdstudio.efp.console.service.facade.KubUserService;
import com.irdstudio.efp.console.service.facade.SDicService;
import com.irdstudio.efp.console.service.vo.KubUserVO;
import com.irdstudio.efp.console.service.vo.SDicVO;
import com.irdstudio.efp.cus.service.facade.CompanyWhiteListService;
import com.irdstudio.efp.cus.service.facade.CusOrgEditService;
import com.irdstudio.efp.cus.service.facade.CusReferrerInfoService;
import com.irdstudio.efp.cus.service.vo.CompanyWhiteListVO;
import com.irdstudio.efp.cus.service.vo.CusOrgEditVO;
import com.irdstudio.efp.cus.service.vo.CusReferrerInfoVO;
import com.irdstudio.efp.esb.api.common.EsbRespServiceHandler;
import com.irdstudio.efp.esb.api.rest.EsbController;
import com.irdstudio.efp.esb.api.rest.yed.req.ReqLoanPerformanceBean;
import com.irdstudio.efp.esb.api.rest.yed.resp.RespLoanPerformanceBean;
import com.irdstudio.efp.esb.api.service.yed.loanManage.YedLoanPerformanceService;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.common.constant.yed.YedCommonConstant;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;

/**
 * 需求编号：【】
 * 问题编号：【】
 * 优e贷业绩归属人和归属机构查询
 *
 * @author zhangxc
 * @version 0.1
 * @date 2020年8月7日16:17:58
 */
@RestController
@RequestMapping("/esb")
public class YedLoanPerformanceController implements EsbController {

    private static Logger logger = LoggerFactory.getLogger(YedLoanPerformanceController.class);
    @Autowired
    private YedLoanPerformanceService yedLoanPerformanceService;
    @Autowired
    @Qualifier("cusReferrerInfoService")
    private CusReferrerInfoService cusReferrerInfoService;
    @Autowired
    private SDicService sDicService;
    @Autowired
    @Qualifier("cusOrgEditService")
    private CusOrgEditService cusOrgEditService;



    /**
     * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("esbReqServiceBean")
    public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
        logger.info("校验 ESB请求系统头和请求应用头对象!");
        EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
        return esbReqServiceBean;
    }

    /**
     * 获取ESB请求对象，校验 ESB请求体对象
     *
     * @param request 请求对象集合
     * @return
     */
    @ModelAttribute("reqLoanPerformanceBean")
    public ReqLoanPerformanceBean getReqEsbBodyBean(HttpServletRequest request) {
        logger.info("校验 ESB请求体对象！");
        String esbReqBody = (String) request.getAttribute("esbReqBody");
        return JSONObject.parseObject(esbReqBody, ReqLoanPerformanceBean.class, Feature.InternFieldNames);
    }

    @PostMapping("/SERVICE_30230021_01")
    public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult bindingResult1,
                                     @Validated @ModelAttribute("reqLoanPerformanceBean") ReqLoanPerformanceBean reqLoanPerformanceBean, BindingResult bindingResult2, Exception exception) {
        try {
            logger.info("======>优e贷业绩归属人和归属机构查询【" + reqLoanPerformanceBean.getPdCd() + "_30230021_01】开始<======");
            // 参数校验
            validateBean(esbReqServiceBean, bindingResult1, reqLoanPerformanceBean, bindingResult2, exception, logger);
            // 设置系统头对象
            setSysHeadFieldThreadLocal(esbReqServiceBean);

            SDicVO sDicVO = new SDicVO();
            sDicVO.setOpttype("STD_ZB_CERT_TYP");
            sDicVO.setEnname(reqLoanPerformanceBean.getIdentTp());
            sDicVO = sDicService.queryOneByennameOpttype(sDicVO);
            if(StringUtils.isBlank(sDicVO.getEnname())){
                //todo 错误码
                //throw new ESBException("证件类型不对，请重输！");
                throw new BizException(EsbBizEnums.RetCodeEnum.JKYDCSJYBTG.getVALUE(), "接口约定参数不通过，请检查！");
            }

            CusReferrerInfoVO cusReferrerInfoVO = CusReferrerInfoVO.builder().prdId(reqLoanPerformanceBean.getPdCd())
                    .certType(reqLoanPerformanceBean.getIdentTp())
                    .certCode(reqLoanPerformanceBean.getIdentNo()).build();

            //推荐人工号
            String referrerId = "";
            //业绩归属人机构号
            String referrerOrg = "";
            //出账机构
            String chargeoffBrId = "";
            String orgName = "";
            //先根据条件从推荐人信息表中查询推荐人工号
            List<CusReferrerInfoVO> list = cusReferrerInfoService.queryCusReferByCond(cusReferrerInfoVO);
            if (null != list && list.size() > 0) {
                referrerId = list.get(0).getReferrerId();
                referrerOrg = list.get(0).getMainBrId();
                if(StringUtils.isNotBlank(referrerOrg)){
                    //添加分支机构名称
                    CusOrgEditVO vo = new CusOrgEditVO();
                    vo.setOrgNo(referrerOrg);
                    CusOrgEditVO cusOrgEditVO = cusOrgEditService.queryByOrgNo(vo);
                    if(Objects.nonNull(cusOrgEditVO) && Objects.nonNull(cusOrgEditVO.getName())){
                        orgName =  cusOrgEditVO.getName();
                    }else{
                        orgName = "广州银行营业部";
                    }
                }
                chargeoffBrId = list.get(0).getChargeOffBrId();

                /*KubUserVO kubUserVO = new KubUserVO();
                kubUserVO.setUserid(referrerId);
                kubUserVO = this.kubUserService.queryByPk(kubUserVO);
                //若客户录入推荐人工号，且推荐人工号在营销业务经理库里存在，则获取推荐人归属机构，将该机构作为管户机构，出账机构与管户机构一致。
                if (null != kubUserVO) {
                    referrerOrg = kubUserVO.getBrchno();
                } else {
                    //否则，通过客户的单位名称匹配企业白名单里的“白名单上报机构号”，若值都不为空，则该机构作为管户机构，由绩效系统分配到该机构对应的虚拟柜员作为管户经理，
                    //出账机构与管户机构一致
                    CompanyWhiteListVO listVO = new CompanyWhiteListVO();
                    listVO.setCompanyName(list.get(0).getWrkCorpNm());
                    List<CompanyWhiteListVO> listVOList = this.companyWhiteListService.queryConditions(listVO);
                    if (null != listVOList && listVOList.size() > 0)
                        referrerOrg = listVOList.get(0).getAppearOrg();
                    else {
                        referrerId = YedCommonConstant.REFERRER_USR;
                        referrerOrg = YedCommonConstant.REFERRER_ORG;
                    }
                }*/
            }
            /*else {
                //否则，将“总行智慧银行中心0043”作为管户机构，由绩效系统分配到该机构对应的虚拟柜员作为管户经理，出账机构定为0328总行营业部。
                referrerId = YedCommonConstant.REFERRER_USR;
                referrerOrg = YedCommonConstant.REFERRER_ORG;
            }*/

            return yedLoanPerformanceService.processYedLoanPerformance(reqLoanPerformanceBean, esbReqServiceBean, referrerOrg, referrerId,chargeoffBrId,orgName);
        } catch (ESBException e) {
            RespLoanPerformanceBean failureRespBean = yedLoanPerformanceService.getFailureRespBean(e.getErrorCode(), e.getMessage());
            // 设置返回信息
            EsbRespServiceBean esbRespServiceBean = EsbRespServiceHandler.esbFailureHandler(esbReqServiceBean, failureRespBean, e.getErrorCode(), e.getMessage());
            return esbRespServiceBean;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            logger.info("======>优e贷业绩归属人和归属机构查询【" + reqLoanPerformanceBean.getPdCd() + "_30230021_01】结束<======");
        }
        return null;
    }


}
